package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.entity.Comment;
import edu.sdbi.judge.domain.entity.News;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.CommentMapper;
import edu.sdbi.judge.mapper.NewsMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 考核5. 	新闻删除
 *
 * @author 周涛
 */
@Order(6)
@Service
public class Judge_6 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private CommentMapper commentMapper;


    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("6");

        String newsId = "1";
        try {
            // 步骤3: 删除新闻
            boolean deleteSuccess = deleteNews(ip, newsId);
            if (!deleteSuccess) {
                studentResult.setScore(0.0);
                studentResult.setResult("删除新闻接口调用失败");
                return studentResult;
            }

            // 步骤4: 验证新闻是否被逻辑删除
            double score = 0.0;
            boolean newsDeleted = verifyNewsIsDeletedInDatabase(newsId);
            String result = "";
            if (newsDeleted) {
                result += "新闻被删除;";
                score += 2;
            }

            // 步骤5: 验证评论是否被逻辑删除
            boolean commentsDeleted = verifyCommentsAreDeletedInDatabase(newsId);
            if (commentsDeleted) {
                result += "评论被删除";
                score += 2;
            }
            studentResult.setResult(result);
            // 全部通过，得4分
            studentResult.setScore(score);

        } catch (Exception e) {
            studentResult.setScore(0.0);
            studentResult.setResult("接口调用异常：" + e.getMessage());
            e.printStackTrace();
        }

        return studentResult;
    }

    /**
     * 删除新闻（正确使用doPost方法）
     */
    private boolean deleteNews(String ip, String newsId) throws Exception {
        String url = "http://" + ip.trim() + "/news/delete?id=" + newsId;

        // 构建请求头（删除接口使用表单格式）
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");

        // 调用doPost方法（请求体为null，因为参数在URL中）
        String result = httpUtil.doPost(url, headers, null);
        if (result == null) {
            return false;
        }

        JSONObject json = JSONObject.parseObject(result);
        return json.getIntValue("code") == 200 && "删除成功".equals(json.getString("msg"));
    }

    /**
     * 验证新闻是否在数据库中被逻辑删除
     */
    private boolean verifyNewsIsDeletedInDatabase(String newsId) {
        News news = newsMapper.selectById(newsId);
        if (news == null) {
            // 物理删除，不符合逻辑删除要求
            return false;
        }
        // 检查deleted字段是否为true
        return news.getIsDelete() == 1;
    }

    /**
     * 验证评论和回复是否在数据库中被逻辑删除
     */
    private boolean verifyCommentsAreDeletedInDatabase(String newsId) {
        // 查询新闻相关评论
        List<Comment> comments = commentMapper.selectByNewsId(newsId);
        if (comments == null) {
            return false;
        }

        for (Comment comment : comments) {
            // 检查评论是否被逻辑删除
            if (comment.getIsDelete() == null || !comment.getIsDelete()) {
                return false;
            }

            // 检查评论的回复是否被逻辑删除
            List<Comment> replies = CommentMapper.selectByCommentId(comment.getId());
            if (replies == null) {
                continue;
            }

            for (Comment reply : replies) {
                if (reply.getIsDelete() == null || !reply.getIsDelete()) {
                    return false;
                }
            }
        }

        return true;
    }
}
